import { Button, Form } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import React, { useCallback, useMemo } from 'react'
import { useRequest } from 'taro-hooks'
import AddressSelect from '../../components/address-select'
import DateTimePicker from '../../components/date-time-picker'
import Layout from '../../components/layout'
import ProductCard from '../../components/product-card'
import { DATE_TIME_OPTIONS } from '../../constants'
import { useNavigation } from '../../hooks'
import { IOrderProduct } from '../../inteface/order'
import { orderSubmit } from '../../services/appointment'
import { getProductListWithPrice } from '../../services/product'
import { getUserAddresses } from '../../services/user'
import { toast } from '../../utils'
import { parseTimeRangeToTimestamps } from '../../utils/formatDate'
import './index.less'

const QuickAppointment: React.FC = () => {
  const { params, redirectTo } = useNavigation()
  const packageId = params.packageId as string
  const [form] = Form.useForm()
  const selectedPackages = Form.useWatch('selectedPackages', form)
  const { data: addressesData, loading } = useRequest(getUserAddresses)
  const { runAsync: addAppointmentRun } = useRequest(orderSubmit, { manual: true })
  const { data: productListData, loading: productListLoading } = useRequest(getProductListWithPrice)

  const initialPackages = useMemo(() => {
    return (
      productListData?.listProduct?.map((item) => {
        return {
          id: item.id,
          name: item.name,
          price: item.totalPrice,
          image: item.style.image,
        }
      }) || []
    )
  }, [productListData])

  // 地址选择器数据
  const addresses = useMemo(() => {
    return (
      addressesData?.addresses?.map((item) => {
        return {
          isDefault: item.isDefault,
          id: item.id,
          addressDetail: item.address,
          name: item.name,
          phone: item.phone,
          cityName: '',
          countyName: '',
          provinceName: '',
          townName: '',
        }
      }) || []
    )
  }, [addressesData?.addresses])

  const onFinish = useCallback(
    (values: any) => {
      const date = values.selectedTime.text + ' ' + values.selectedTime.children?.[0]?.text
      const timestamps = parseTimeRangeToTimestamps(date)

      // 2025-10-12 11:00-12:00
      const data: IOrderProduct = {
        beginAt: timestamps?.[0] || 0,
        endAt: timestamps?.[1] || 0,
        addressId: values.selectedAddress,
        products: values.selectedPackages.map((item: string) => ({
          productId: item,
        })),
      }
      addAppointmentRun(data).then((res) => {
        redirectTo({
          url: `/pages/appointment-success/index?orderNo=${res?.result?.orderNo}`,
        })
      })
    },
    [addAppointmentRun, redirectTo],
  )

  return (
    <Layout
      title='快速预约'
      showTabBar={false}
      fullLoading={loading || productListLoading}
      footer={
        <View className='p-16'>
          <Button
            block
            type='primary'
            onClick={() => {
              form.validateFields().then((values) => {
                if (values.length) {
                  toast.showError(values[0].message)
                } else {
                  form.submit()
                }
              })
            }}>
            确认预约(已选{selectedPackages?.length}个套餐)
          </Button>
        </View>
      }>
      <View className='content-wrapper'>
        <Form
          initialValues={{
            selectedAddress: addressesData?.addresses?.find((item) => item.isDefault)?.id,
            selectedPackages: packageId ? [packageId] : [],
          }}
          form={form}
          onFinish={onFinish}
          divider>
          {/* 地址选择 */}
          <View className='form-header'>
            <Text>选择地址</Text>
          </View>
          <Form.Item name='selectedAddress' noStyle rules={[{ required: true, message: '请选择地址' }]}>
            <AddressSelect options={addresses} />
          </Form.Item>

          {/* 时间选择 */}
          <View className='form-header'>
            <Text>选择时间</Text>
          </View>
          <Form.Item name='selectedTime' noStyle rules={[{ required: true, message: '请选择时间' }]}>
            <DateTimePicker options={DATE_TIME_OPTIONS} />
          </Form.Item>

          {/* 套餐选择 */}
          <View className='form-header'>
            <Text>装修项目</Text>
            <Text className='form-header-desc'>请选择您的 装修项目</Text>
          </View>
          <Form.Item name='selectedPackages' noStyle rules={[{ required: true, message: '请选择套餐' }]}>
            <ProductCard options={initialPackages} />
          </Form.Item>
        </Form>
      </View>
    </Layout>
  )
}

export default QuickAppointment
